<template>
  <div class="create-folder-container">
    <!-- 带文字提示的新建按钮 -->
    <div class="create-folder-button-container" v-if="!showCreateDialog">
      <el-button
          type="success"
          plain
          @click="showCreateDialog = true"
          class="create-btn"

      >
        新建文件夹
      </el-button>
    </div>

    <div class="create-folder-dialog" v-if="showCreateDialog">
      <div class="dialog-content">
        <div class="dialog-header">
          <h3>创建新文件夹</h3>
          <el-icon class="close-icon" @click="handleDialogClose">
            <CloseBold />
          </el-icon>
        </div>
        
        <el-input
            v-model="folderFormData.name"
            placeholder="新文件夹名"
            @keyup.enter="handleCreateFolder"
            :maxlength="64"
            class="folder-input"
        >
          <template #prepend>
            <el-icon>
              <FolderAdd />
            </el-icon>
          </template>
        </el-input>
        
        <div class="button-group">
          <el-button
              type="success"
              plain
              size="small"
              @click="handleCreateFolder"
              :icon="Select"
          >
            确定
          </el-button>
          <el-button
              type="danger"
              size="small"
              plain
              @click="handleDialogClose"
              :icon="CloseBold"
          >
            取消
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, CloseBold, FolderAdd, Select } from '@element-plus/icons-vue'
import { createNewFolderApi } from '@/utils/API/file-core/Index.js'
import { getLocalStroage } from "@/utils/LocalStroageUtil";
import { validateFileName } from '@/utils/validate.js'  // 新增工具函数导入

// 定义可触发的事件
const emit = defineEmits(['folder-created'])

const showCreateDialog = ref(false)
const folderFormData = reactive({})

const props = defineProps({
  pathStack: {
    type: Array,
    required: true,
  }
})

// 处理对话框关闭事件（重置输入）
const handleDialogClose = () => {
  folderFormData.name = ''
  showCreateDialog.value = false
}

// 面包屑封装成字符串（修正后）
const filteredBreadcrumb = () => {
  // 根目录返回空字符串（根据后端需求可能需要调整为 '/'）
  if (props.pathStack.length === 0) return '/';
  // 非根目录提取每个目录的fileName并用斜杠连接（如 [ {fileName: "文档"}, {fileName: "项目"} ] -> "文档/项目/"）
  const pathNames = props.pathStack.map(dir => dir.fileId);
  return '/' + pathNames.join('/') + '/';
}

// 优化创建逻辑：使用工具函数校验名称
const handleCreateFolder = async () => {
  const folderName = folderFormData.name.trim()
  
  // 使用工具函数校验名称
  const validateResult = validateFileName(folderName)
  if (validateResult !== true) {
    ElMessage.warning(validateResult)  // 直接使用工具返回的错误信息
    return
  }

  try {
    const response = await createNewFolderApi({
      fileName: folderName,
      filePath: filteredBreadcrumb(),
      fileType: 'folder',
      isDirectory: true,
      ownerId: getLocalStroage().userId,
    })

    if (response.code === 200) {
      ElMessage.success(response.msg)
      handleDialogClose()
      emit('folder-created')
    } else {
      ElMessage.error(response.msg || '文件夹创建失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败：' + error.message)
  }
}
</script>

<style scoped>
.create-folder-container {
  position: relative;
}

.create-btn {
  margin: 15px 0;
  padding: 8px 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.create-folder-dialog {
  position: absolute;
  top: 0;
  left :0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  width: 380px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.close-icon {
  cursor: pointer;
  font-size: 18px;
  color: #909399;
}

.folder-input {
  margin-bottom: 15px;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}

.el-input-group__prepend {
  background-color: #f5f7fa;
}
</style>